var express = require("express");
var router = express.Router();
var { rideruserModel, chargeModel } = require("../db/rider");
var { orderModel } = require("../db/order_model");
var moment = require("moment");
var { userModel } = require("../db/user_model");
// router.get("/ridertable", async (req, res) => {
//   let pageSize = req.query.pageSize;
//   let currentPage = req.query.currentPage;
//   let data = [];
//   let obj = { isdelete: false };
//   let idNumber = req.query.idNumber;
//   let namephone = req.query.namephone;
//   let done = req.query.done;
//   let startTime = req.query.startTime;
//   let endTime = req.query.endTime;
//   if (namephone) {
//     obj.$or = [{ username: RegExp(namephone) }, { phone: RegExp(namephone) }];
//   }

router.get("/ridertable",async(req,res)=>{
    let pageSize = req.query.pageSize
    let currentPage = req.query.currentPage
    let data =[]
    let obj={isdelete:false}
    let idNumber=req.query.idNumber
    let namephone=req.query.namephone
    let done=req.query.done
    let startTime=req.query.startTime
    let endTime=req.query.endTime
   if(namephone){
    obj.$or=[{username:RegExp(namephone)},{phone:RegExp(namephone)}]
   }
   if(idNumber){
       obj.Idcard={$regex:idNumber}
   }
   if(done!="all"){
       obj.status={$regex:done}
   }
   if(startTime&endTime){
    obj.date_birth={$gte:startTime,$lte:endTime}
   }else if(startTime){
       obj.date_birth={$gte:startTime}
   }else if(endTime){
    obj.date_birth={$lte:endTime}
}
    let list = await (await rideruserModel.find(obj).sort({date_birth:-1}).skip((currentPage-1)*pageSize).limit(pageSize).lean())
    let a=await rideruserModel.find(obj)
    list.forEach(async item=>{
        let orderdata=await orderModel.find({rid:item._id,attitude:{$gte:0}})
        item.point=0
        let point=0
        orderdata.forEach(item2=>{
            point+=item2.attitude+item2.speed
        })
        if(orderdata.length>0){
            item.point=point/(2*orderdata.length)
        }
        console.log(item.point);
    })
    setTimeout(() => {
        console.log(list,2222);

        res.send({
          code: 200,
          msg: "展示成功",
          data: list,
          total:a.length,
          a
        });
    }, 100);
   
})


router.post("/addrider",async(req,res)=>{
    let data =await rideruserModel.create({...req.body})
  if (idNumber) {
    obj.Idcard = { $regex: idNumber };
  }
  if (done != "all") {
    obj.status = { $regex: done };
  }
  if (startTime & endTime) {
    obj.date_birth = { $gte: startTime, $lte: endTime };
  } else if (startTime) {
    obj.date_birth = { $gte: startTime };
  } else if (endTime) {
    obj.date_birth = { $lte: endTime };
  }
  let list = await rideruserModel
    .find(obj)
    .sort({ date_birth: -1 })
    .skip((currentPage - 1) * pageSize)
    .limit(pageSize);
  let a = await rideruserModel.find(obj);
  console.log(a, "aaa");
  res.send({
    code: 200,
    msg: "展示成功",
    data: list,
    total: a.length,
    a,
  });
});

router.post("/addrider", async (req, res) => {
  let data = await rideruserModel.create({ ...req.body });
  res.send({
    code: 200,
    msg: "添加",
    data,
  });
});

router.post("/auditrider", async (req, res) => {
  console.log(req.body);
  let id = req.body.id;
  let status = req.body.status;
  let desc = req.body.desc;
  let data = await rideruserModel.updateOne(
    { _id: id },
    { $set: { status, desc } }
  );
  res.send({
    code: 200,
    msg: "审核成功",
    data,
  });
});
router.post("/deleterider", (req, res) => {
  let arr = req.body.ids;
  arr.forEach(async (item) => {
    let data = await rideruserModel.updateOne(
      { _id: item._id },
      { $set: { isdelete: true } }
    );
  });
  res.send({
    code: 200,
    msg: "删除成功",
  });
});
router.post("/stoprider", (req, res) => {
  console.log(req.body);
  let arr = req.body.ids;
  let isStop = req.body.isStop;
  arr.forEach(async (item) => {
    let data = await rideruserModel.updateOne(
      { _id: item._id },
      { $set: { isStop } }
    );
  });
  res.send({
    code: 200,
    msg: "删除成功",
  });
});

router.get("/tabardata", async (req, res) => {
  let data = {};
  let today = new Date(Date.now() + 8 * 60 * 60 * 1000);
  let endday0 = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
  let endday1 = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
  let a1 = await orderModel.aggregate([
    {
      $match: {
        place: {
          $lte: today,
          $gte: endday0,
        },
        statue: "已完成",
      },
    },
    {
      $project: {
        year: {
          $year: "$place",
        },
        month: {
          $month: "$place",
        },
        day: {
          $dayOfMonth: "$place",
        },
        _id: 1,
      },
    },
    {
      $group: {
        _id: "$day",
        count: {
          $sum: 1,
        },
      },
    },
  ]);
  let a2 = await orderModel.aggregate([
    {
      $match: {
        place: {
          $lte: today,
          $gte: endday0,
        },
        statue: "已取消",
      },
    },
    {
      $project: {
        year: {
          $year: "$place",
        },
        month: {
          $month: "$place",
        },
        day: {
          $dayOfMonth: "$place",
        },
        _id: 1,
      },
    },
    {
      $group: {
        _id: "$day",
        count: {
          $sum: 1,
        },
      },
    },
  ]);

  let b1 = await orderModel.aggregate([
    {
      $match: {
        place: {
          $lte: today,
          $gte: endday1,
        },
        statue: "已完成",
      },
    },
    {
      $project: {
        year: {
          $year: "$place",
        },
        month: {
          $month: "$place",
        },
        day: {
          $dayOfMonth: "$place",
        },
        _id: 1,
      },
    },
    {
      $group: {
        _id: "$day",
        count: {
          $sum: 1,
        },
      },
    },
  ]);

  let b2 = await orderModel.aggregate([
    {
      $match: {
        place: {
          $lte: today,
          $gte: endday1,
        },
        statue: "已取消",
      },
    },
    {
      $project: {
        year: {
          $year: "$place",
        },
        month: {
          $month: "$place",
        },
        day: {
          $dayOfMonth: "$place",
        },
        _id: 1,
      },
    },
    {
      $group: {
        _id: "$day",
        count: {
          $sum: 1,
        },
      },
    },
  ]);
  var ddd = new Date();
  ddd.setFullYear(ddd.getFullYear - 1);

  let c1 = await orderModel.aggregate([
    {
      $match: {
        place: {
          $lte: today,
          $gte: ddd,
        },
        statue: "已完成",
      },
    },
    {
      $project: {
        year: {
          $year: "$place",
        },
        month: {
          $month: "$place",
        },
        day: {
          $dayOfMonth: "$place",
        },
        _id: 1,
      },
    },
    {
      $group: {
        _id: "$month",
        count: {
          $sum: 1,
        },
      },
    },
  ]);

  let c2 = await orderModel.aggregate([
    {
      $match: {
        place: {
          $lte: today,
          $gte: ddd,
        },
        statue: "已取消",
      },
    },
    {
      $project: {
        year: {
          $year: "$place",
        },
        month: {
          $month: "$place",
        },
        day: {
          $dayOfMonth: "$place",
        },
        _id: 1,
      },
    },
    {
      $group: {
        _id: "$month",
        count: {
          $sum: 1,
        },
      },
    },
  ]);

  res.send({ a1, a2, b1, b2, c1, c2 });
});

router.get("/mapdate", async (req, res) => {
  let data = await orderModel.find();
  let reg = /.+?(省|市|自治区|自治州|县|区)/g;
  data.forEach((item) => {
    if (item.deliveryAddress.fuzzyaddress) {
      let arr = item.deliveryAddress.fuzzyaddress.match(reg);
      item.mapdata = item.deliveryAddress.fuzzyaddress.match(reg);
    }
  });
  let province = {};
  let city = {};
  let county = {};
  let Address = {};
  for (let k = 0; k < data.length; k++) {
    if (data[k].mapdata) {
      a = data[k].mapdata;
      if (province[a[0]]) {
        province[a[0]]++;
      } else {
        province[a[0]] = 1;
      }
      if (city[a[0] + a[1]]) {
        city[a[0] + a[1]]++;
      } else {
        city[a[0] + a[1]] = 1;
      }
      if (county[a[0] + a[1] + a[2]]) {
        county[a[0] + a[1] + a[2]]++;
      } else {
        county[a[0] + a[1] + a[2]] = 1;
      }

      if (Address[data[k].deliveryAddress.fuzzyaddress]) {
        Address[data[k].deliveryAddress.fuzzyaddress]++;
      } else {
        Address[data[k].deliveryAddress.fuzzyaddress] = 1;
      }
    }
  }
  res.send({ province, city, county, Address });
});

router.get("/numdata", async (req, res) => {
  let data1 = await rideruserModel.find();
  let ridernum = data1.length;
  let data2 = await orderModel.find();
  let ordernum = data2.length;
  let data3 = await userModel.find();
  let usernum = data3.length;
  res.send({ ridernum, ordernum, usernum });
});

router.get("/charge", async (req, res) => {
  let data = await chargeModel.find();
  console.log(data);
  res.send(data);
});

router.post("/upcharge", async (req, res) => {
  console.log(req.body);
  let obj = req.body;
  let id = obj._id;
  delete obj._id;
  console.log(obj);
  let data = await chargeModel.updateOne({ _id: id }, obj);
});

router.get("/riderFind", async (req, res) => {
  let data = await orderModel.find({ rid: req.query.rid });
  console.log(data.length);
  let arr = [];
  data.map((item) => {
    arr.push(moment(item.takeTime).format("YYYY-MM-DD"));
  });
  console.log(arr);
  res.send(arr);
});
router.get("/order", async (req, res) => {
  let data = await orderModel.find({ rid: req.query.rid });
  res.send(data);
});

// 获取骑手信息
router.get("/get_riger", async (req, res) => {
  console.log(req.query);
  const data = await rideruserModel.find().where({
    _id: req.query.id,
  });
  total = data.length;
  if (data.length > 0) {
    res.send({
      code: 200,
      msg: "展示成功",
      data: data,
      total: total,
    });
  } else {
    res.send({
      code: 304,
      msg: "暂无当前骑手",
      data: [],
      total: total,
    });
  }
});
// 修改手机号
router.get("/get_riger_phone", async (req, res) => {
  console.log(req.query);
  let query = req.query;
  const dataid = await rideruserModel.find().where({
    _id: req.query.id,
  });
  if (dataid[0].phone != req.query.phone) {
    const data = await rideruserModel.find().where({
      phone: req.query.phone,
    });
    total = data.length;
    if (data.length > 0) {
      res.send({
        code: 203,
        msg: "手机号已被注册",
        data: data,
        total: total,
      });
    } else {
      await rideruserModel.updateOne({ _id: req.query.id }, { $set: query });
      res.send({
        code: 200,
        msg: "修改成功",
        data: [],
        total: total,
      });
    }
  }
});

// 修改骑手信息
router.put("/edit_rider/:id", async function (req, res) {
  let body = req.body;
  console.log(body);
  try {
    await rideruserModel.updateOne({ _id: req.params.id }, { $set: body });
    res.send({
      code: 200,
      msg: "修改成功",
    });
  } catch (err) {
    console.error("Failed to insert facility into MongoDB:", err);
    res.status(500).send({ error: "Server error" });
  }
});
module.exports = router;
